<template>
  <view v-if="true" class="uni-app">
    <view class="status-bar" />

    <wk-nav-bar
      :command-list="commandList"
      :refresh-prev="refreshPrevPage"
      title="询价单明细"
      theme="white"
      class="nav-bar"
      @command="handleCommand" />

    <!-- @scrolltolower="handleScrollTolower" -->
    <scroll-view
      :scroll-y="true"
      class="main-container scroll-view-hook">
      <view class="header-top">
        <view class="bg linear-gradient" />
        <view class="card">
          <view class="title-cell">
            <!-- <image :src="$static('images/crm/gray_customer.png')" class="type-icon" /> -->
            <view class="title-text">
              <text class="text">
                询价单标题：{{ orderTitle.title }}
              </text>
              <text v-if="detailData.status === 2" class="wk wk-lock" />
            </view>
            <!-- <view :class="detailData.dealStatus === 1 ? 'success' : 'info'" class="title-status">
              <text>{{ detailData.dealStatus === 1 ? '已成交' : '未成交' }}</text>
            </view> -->
          </view>
          <!-- TODO数据绑定 -->
          <view class="main-info">
            <view class="info-item">
              询价单号：{{ detailData.mobile || '&#45;&#45;' }}
            </view>
            <view class="info-item">
              询价方式：{{ detailData.mobile || '&#45;&#45;' }}
            </view>
          </view>

          <!-- <image
            v-if="detailData.mobile"
            :src="$static('images/icon/call_up.png')"
            class="call-up"
            @click="ringUp(detailData.mobile)" /> -->

          <!-- <view class="main-info">
            <flow-progress
              v-if="detailData"
              :type="comType"
              :detail-id="id"
              :detail-data="detailData" />
          </view>

          <view
            v-if="auditInfo && auditInfo.isCheck === 1"
            class="check-box">
            <view class="btn success" @click="handleAuditAction('pass')">
              <text class="wk wk-check-fill icon" />
              <text>通过</text>
            </view>
            <view class="btn error" @click="handleAuditAction('refuse')">
              <text class="wk wk-close-fill icon" />
              <text>拒绝</text>
            </view>
          </view> -->
        </view>
      </view>

      <view ref="wkTabs" class="wk-tabs">
        <view
          v-for="(tab, index) in tabs"
          :key="index"
          :class="{active: activeTab === tab.value}"
          class="wk-tab-item"
          @click="handleToggleTabs(tab.value)">
          {{ tab.label }}
        </view>
      </view>
      <!-- 基本信息 -->
      <wk-keep-alive v-model="activeTab">
        <wk-keep-alive-item>
          <detail-base-info :detail-id="id" :type="comType" :insert-fields="orderData" class="detail-container" />
        </wk-keep-alive-item>
        <!-- 报价须知 -->
        <wk-keep-alive-item>
          <quota-notice
            ref="activity"
            :detail-id="id"
            :type="comType"
            activity-title="客户" />
        </wk-keep-alive-item>

        
        <!-- 报价轮次-->
        <wk-keep-alive-item>
          <quota-round
            :detail-id="id"
            :detail-data="detailData"
            :batch-id="detailData.batchId"
            class="detail-about-container" />
        </wk-keep-alive-item>

        <!-- 附件列表 -->
        <wk-keep-alive-item>
          <attach-file :detail-id="id" :type="comType" class="detail-container" />
        </wk-keep-alive-item>
      </wk-keep-alive>
    </scroll-view>

    <!-- <uni-popup ref="popup" type="dialog">
      <uni-popup-dialog
        :content="dialogMsg"
        type="warning"
        @confirm="handleDialogConfirm" />
    </uni-popup> -->
  </view>
</template>

<script>

  import { getsysMessageDetail} from 'API/notice';

  import DetailBaseInfo from './components/detailSection/baseInfo'
  import AttachFile from './components/detailSection/attachFile'
  import QuotaNotice from './components/detailSection/quotaNotice'
  import QuotaRound from './components/detailSection/quotaRound'
  import {srmXjOrderById} from 'API/inqueryMessage'

  // import UniPopup from '@/components/uni-popup/uni-popup';
  // import UniPopupDialog from '@/components/uni-popup-dialog/uni-popup-dialog';
  // import WkActionSheet from '@/components/wk-action-sheet/wk-action-sheet';

  export default {
    name: 'CustomerDetail',
    components: {
      // WkActionSheet,
      // UniPopupDialog,
      // UniPopup,
      DetailBaseInfo,
      AttachFile,
      QuotaNotice,
      QuotaRound,
    },
    onLoad(e) {
      this.id = e.id
      this.objId = e.objId
    },
    data() {
      return {
        xjtypes: [
          '--',
          '询比价',
          '定向采购',
          '竞争性磋商'
        ],
        id: null,
        objId: null,
        orderTitle: {
          title: '--',
          xjOrder: '--',
          xjFs: xjtypes['0']
        },
        orderData: [],
        detailData: {},
        routerQuery: {},
        auditInfo: undefined,
        
        tabs: [
          { label: '基本信息', value: 0 },
          { label: '报价须知', value: 1 },
          { label: '附件列表', value: 3 }, 
          { label: '报价轮次', value: 2 }
        ],
        activeTab: 0,
        
        // commandValue: null,
        // dialogMsg: '',
        
        refreshPrevPage: false,
        comType: 'crm_customer', // TODO 需要修改
        mainUserInfo: {},

        commandList: [
          {
            label: '转移',
            imgIcon: 'transfer',
            auth: 'crm.customer.transfer',
            value: 'transfer'
          },
          {
            label: '锁定',
            imgIcon: 'lock',
            auth: 'crm.customer.lock',
            value: 'lock'
          },
          {
            label: '放入公海',
            imgIcon: 'putinpool',
            auth: 'crm.customer.putinpool',
            value: 'putinpool'
          },
          {
            label: '更改成交状态',
            imgIcon: 'dealStatus',
            auth: 'crm.customer.dealStatus',
            value: 'dealStatus'
          },
          {
            label: '编辑',
            imgIcon: 'update',
            auth: 'crm.customer.update',
            value: 'update'
          },
          {
            label: '删除',
            imgIcon: 'delete',
            auth: 'crm.customer.delete',
            value: 'delete'
          },
        ],
        projectTypes: [
          '--',
          '航空零组件',
          '航空器材',
          '地面器材',
          '劳保及办公用品',
          '设备设施'
        ],
        // 需方看的状态
        orderStates: [
          '--',
          '待询价',
          '询价中',
          '已结束询价待审批',
          '询价审批中',
          '定标审批被驳回',
          '定标审批通过',
          '已发布中标通知'
        ],
        // 供应商看的状态
        gysOrderStates: [
          '--',
          '待参与',
          '已放弃',
          '报价中',
          '报价已提交',
          '已中标',
          '未中标'
        ],
      }
    },
    mounted() {
      this.getDetail()
    },
    methods: {
      handleToggleTabs(val) {
        this.activeTab = val
      },
      getDetail() {
        console.log('getDetail')
        getsysMessageDetail(this.id).then(res => {
          console.log('detail: ', res)
          this.detailData = res
        }).catch((err) => {
          console.log('err', err)
          // this.goBack()
        })
        srmXjOrderById({
          id: this.objId
        }).then(res => {
          console.log('order: ', res)
          let data = res.data
          this.orderData = [
            {
              name: '采购组织',
              value: data.buyerUnitName,
              formType: 'info'
            },
            {
              name: '币种',
              value: data.currency == '01' ? '人民币' : '美元',
              formType: 'info'
            },
            {
              name: '项目类型',
              value: this.projectTypes[data.projectType] == undefined ? this.projectTypes[0] : this.projectTypes[data.projectType],
              formType: 'info'
            },
            {
              name: '采购员',
              value: data.userName,
              formType: 'info'
            },
            {
              name: '采购部门',
              value: data.unitName,
              formType: 'info'
            },
            {
              name: '轮次',
              value: data.rounds,
              formType: 'info'
            },
            {
              name: '发布日期',
              value: data.publishDateTime,
              formType: 'info'
            },
            {
              name: '订单状态',
              value: this.gysOrderStates[data.gysOrderState] || this.orderStates[data.orderState],
              formType: 'info'
            },
            {
              name: '附件',
              value: data.fileSrc,
              formType: 'file'
            },
            {
              name: '是否整单报价',
              value: data.isZdXj,
              formType: 'info'
            },
            {
              name: '备注',
              value: data.remark,
              formType: 'info'
            },
            // checkRole('cgy_role')
            // {
            //   name: '询价备注',
            //   value: data.buyerRemark,
            //   formType: 'info'
            // },
            // checkRole('gys_role')
            // {
            //   name: '开标说明',
            //   value: data.dingbiaoRemark,
            //   formType: 'info'
            // },
          ]
          console.log('res', res)
        })
      },

      /**
       * 获取审批流
       */
      getAuditInfo() {
      },

      /**
       * 获取首要联系人详情
       */
      getMainUser() {
      },

      /**
       * 渲染更多操作选项
       */
      renderCommands() {
        this.commandList = [
          {label: '查看审批流', imgIcon: 'read', noCheck: true, value: 'read'},
          {label: '转移', imgIcon: 'transfer', auth: 'crm.contract.transfer', value: 'transfer'},
          {label: '编辑', imgIcon: 'update', auth: 'crm.contract.update', value: 'update'},
          {label: '合同作废', imgIcon: 'discard', auth: 'crm.contract.discard', value: 'discard'},
          {label: '删除', imgIcon: 'delete', auth: 'crm.contract.delete', value: 'delete'}
        ]
        // 判断是否能够撤回审批
        let index = this.commandList.findIndex(item => item.label === '撤回审批')
        if (this.auditInfo && this.auditInfo.isRecheck === 1 && index === -1) {
          this.commandList.splice(1, 0, {
            label: '撤回审批',
            imgIcon: 'reset',
            noCheck: true,
            value: 'reset'
          })
        } else if (this.auditInfo && this.auditInfo.isRecheck !== 1 && index !== -1) {
          this.commandList.splice(index, 1)
        }
        index = null

        // 如果没有审批流则删除查看审批流
        index = this.commandList.findIndex(item => item.value === 'read')
        if (index !== -1 && !this.detailData.examineRecordId) {
          this.commandList.splice(index, 1)
        }
        index = null

        const checkStatus = this.detailData.checkStatus

        // 判断是否能编辑
        index = this.commandList.findIndex(item => item.value === 'update')
        if (index !== -1) {
          // 审核拒绝  审核撤回 未提交才能编辑
          // if (
          //   this.userInfo.userId !== this.detailData.createUserId ||
          //   (![2, 4, 5].includes(checkStatus) && this.detailData.examineRecordId)) {
          //   this.commandList.splice(index, 1)
          // }
          if (![2, 4, 5].includes(checkStatus) && this.detailData.examineRecordId) {
            this.commandList.splice(index, 1)
          }
        }
        index = null

        // 判断是否能删除
        index = this.commandList.findIndex(item => item.value === 'delete')
        if (index !== -1) {
          // 已撤回 未提交 作废 并且是超管才能删除
          if (!this.detailData.isAdmin === 1 ||
            (![4, 5, 8].includes(checkStatus) && this.detailData.examineRecordId)) {
            this.commandList.splice(index, 1)
          }
        }

        // 判断是否能作废
        index = this.commandList.findIndex(item => item.value === 'discard')
        if (index !== -1) {
          // 审核通过，有作废权限才能作废合同
          if (checkStatus !== 1) {
            this.commandList.splice(index, 1)
          }
        }

        // 如果合同已作废
        if (checkStatus === 8) {
          this.commandList = this.commandList.filter(item => ['read', 'delete'].includes(item.value))
        }
      },

      handleCommand(command) {
        // this.commandValue = command.value
        // switch (command.value) {
        // case 'read':
        //   this.$Router.navigateTo({
        //     url: '/pages_crm/auditList',
        //     query: {id: this.detailData.examineRecordId, u_id: this.detailData.ownerUserId}})
        //   break
        // case 'transfer':
        //   this.handleToChangeOwnerUser()
        //   break
        // case 'lock':
        //   this.dialogMsg = `您确定要${command.label}该客户吗？`
        //   this.$refs.popup.open()
        //   break
        // case 'putinpool':
        //   this.handleToChoosePool()
        //   break
        // case 'dealStatus':
        //   this.dialogMsg = `您确定要将该客户更改为${this.detailData.dealStatus === 0 ? '已成交' : '未成交'}吗？`
        //   this.$refs.popup.open()
        //   break
        // case 'update':
        //   this.handleEdit()
        //   break
        // case 'delete':
        //   this.dialogMsg = '您确定要删除该客户吗？'
        //   this.$refs.popup.open()
        //   break
        // }
      },

      handleDialogConfirm(next) {
        switch (this.commandValue) {
        case 'lock':
          this.lockCustomer()
          break
        case 'dealStatus':
          this.changeDealStatus()
          break
        case 'delete':
          this.deleteCustomer()
          break
        }
        next()
      },

      /**
       * 审核操作
       * @param action 审核动作
       */
      handleAuditAction(action) {
      },

      /**
       * 审核
       * @param form 审核信息
       */
      handleAudit(form) {
      },

      handleToChoosePool() {
      },


      /**
       * 转移
       * @param {Object} user
       */
      handleTransfer(user) {
      },

      toContactsDetail() {
        if (!this.mainUserInfo.contactsId) return
        this.$Router.navigateTo({
          url: '/pages_crm/contacts/detail',
          query: {
            id: this.mainUserInfo.contactsId
          }
        })
      },

      /**
       * 锁定/解锁
       */
      lockCustomer() {
      },

      /**
       * 更改成交状态
       */
      changeDealStatus() {
      },

      /**
       * 放入公海
       */
      seasCustomer(data) {
        UpdateCustomerByIds({
          ids: [this.id],
          poolId: data.poolId
        }).then(() => {
          this.$toast('放入公海成功')
          this.$refreshAndToPrev(this)
        })
      },

      /**
       * 删除
       */
      deleteCustomer() {
        DeleteByIds([this.id]).then(() => {
          this.$toast('删除成功')
          this.$refreshAndToPrev(this)
        })
      },
    }
  }
</script>

<style scoped lang="scss">
	@import "style/detail.scss";

	.header-top {
		.card {
			.title-status {
				&.success {
					color: #FFFFFF;
					background-color: #FF8700;
				}
				&.info {
					color: #BBBBBB;
					background-color: #EEEEEE;
				}
			}

			.main-info {
				margin-bottom: 25rpx;
			}

			.call-up {
				position: absolute;
				right: 20rpx;
				top: 105rpx;
				width: 116rpx;
				height: 116rpx;
			}
		}
	}
</style>
